<template>
  <main class="users_add_dia_main">
    <el-dialog :visible="addVis" @close="handleClose" title="新增用户" width="1000px">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="110px">
        <div v-for="item in formColumns" :key="item.props">
          <el-form-item v-if="item.show" :prop="item.props" :label="item.label">
            <!-- 单选按钮 -->
            <el-radio-group
              size="mini"
              v-if="item.ele === 'radio'"
              v-model="formData[item.props]"
              @input="handleradioGroupChange"
            >
              <el-radio v-for="it in item.radios" :key="it.label" :label="it.value">{{ it.label }}</el-radio>
            </el-radio-group>
            <!-- 多选框 -->
            <el-select size="mini" v-if="item.ele === 'select'" v-model="formData[item.props]" style="width: 50%" clearable>
              <el-option v-for="it in item.options" :key="it.value" :label="it.label" :value="it.value">{{
                it.label
              }}</el-option>
            </el-select>
            <!-- input框 -->
            <el-input
              size="mini"
              v-if="item.ele === 'input'"
              v-model="formData[item.props]"
              style="width: 50%"
              placeholder="请输入"
              clearable
            ></el-input>
            <!-- 💭企查查 -->
            <div v-if="item.ele === 'qichachaItem'">
              <el-input
                v-if="inputType"
                size="mini"
                v-model="formData.sponsorName"
                placeholder="请输入关键字"
                style="width: 50%"
              ></el-input>
              <el-select
                v-else
                filterable
                v-model="formData.sponsorName"
                placeholder="请选择"
                clearable
                style="width: 50%"
              >
                <el-option v-for="item in optionsList" :key="item.Name" :label="item.Name" :value="item.Name">
                </el-option>
              </el-select>
              <el-button style="margin-left: 12px" v-if="inputType" size="mini" type="primary" @click="handleGetOptions"
                >查询</el-button
              >
              <el-button style="margin-left: 12px" v-else size="mini" type="primary" @click="handleReset"
                >重置</el-button
              >
              <p class="search-tips">为保证数据的搜索效率，每次查询只返回五条选择项，请您尽可能多输入一些关键字</p>
            </div>
            <!-- 用户特殊下拉框 -->
            <MemberRollingSelect
              v-if="item.ele === 'user'"
              :width="50"
              :value="formData.user"
              @change="onRollingSelectChange($event)"
            ></MemberRollingSelect>
          </el-form-item>
        </div>

        <!-- table表格 -->
        <el-form-item v-if="isShowTable" prop="userList">
          <el-table :data="formData.userList" height="200">
            <el-table-column prop="nickname" label="姓名" align="center">
              <template v-slot="{ row }">
                <el-input clearable size="mini" v-model="row.nickname"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="mobile" label="手机号" align="center">
              <template v-slot="{ row }">
                <el-input clearable size="mini" v-model="row.mobile"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="email" label="邮箱" align="center">
              <template v-slot="{ row }">
                <el-input clearable size="mini" v-model="row.email"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="password" label="密码" align="center">
              <template v-slot="{ row }">
                <el-input clearable size="mini" v-model="row.password"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template v-slot="{ row }">
                <el-button type="text" @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button icon="el-icon-plus" size="mini" style="margin-top: 12px" @click="addNewOneTable"
            >新增一条</el-button
          >
        </el-form-item>
      </el-form>
      <!-- 按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="handleConfirm">确认</el-button>
        <el-button size="mini" @click="handleClose">取消</el-button>
      </span>
    </el-dialog>
  </main>
</template>

<script>
import { mapActions } from 'vuex'
import MemberRollingSelect from './member-rolling-select.vue'
export default {
  components: {
    MemberRollingSelect,
  },
  props: {
    addVis: {
      type: Boolean,
      default: false,
    },
    diaIsAdd: {
      type: Boolean,
      default: true,
    },
    roleOptions: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      // 表单规则
      formColumns: [
        {
          ele: 'radio',
          props: 'source',
          label: '来源：',
          radios: [
            { label: '新用户', value: 0 },
            { label: '系统用户', value: 1 },
          ],
          show: true,
        },
        { ele: 'user', props: 'user', label: '用户：', options: [], show: false },
        { ele: 'select', props: 'roleId', label: '角色：', options: [], show: true },
        { ele: 'qichachaItem', props: 'orgName', label: '所属单位：', show: true },
      ],
      // 表单数据
      formData: {
        source: 0,
        roleId: '',
        roleIds: [],
        user: '',
        orgName: '',
        userList: [],
        // 💭企查查
        sponsorName: '',
      },
      // 表单校验
      formRules: {
        source: [{ required: true, message: '请选择', trigger: 'blur' }],
        user: [{ required: true, message: '未选择或选择不准确', trigger: 'change' }],
        roleId: [{ required: true, message: '请选择', trigger: 'blur' }],
        userList: [{ validator: this.validatorTable }],
        orgName: [{ validator: this.validatorSponsorName }],
      },
      // 💭企查查
      inputType: true,
      optionsList: [],
      isShowTable: true,
    }
  },
  watch: {
    addVis(newV) {
      if (newV) {
        this.getRoleData()
      }
    },
  },
  methods: {
    ...mapActions('projectList', ['qryProviderNameByName']), // 企查查接口

    onRollingSelectChange(obj) {
      this.formData.user = obj.value
    },

    // 获取全部角色
    getRoleData() {
      this.formColumns[2].options = this.roleOptions.map(item => {
        return {
          label: `${item.name}（${item.code}）`,
          value: item.id,
        }
      })
    },
    // 💭企查查
    // 重置
    handleReset() {
      this.inputType = true
      this.formData.sponsorName = ''
    },
    handleGetOptions() {
      if (!this.formData.sponsorName) {
        this.$message.error('请输入关键字查询~')
        return
      }
      this.inputType = false
      const data = {
        searchName: this.formData.sponsorName,
      }
      this.qryProviderNameByName({ data }).then(res => {
        const { code, data = [] } = res
        if (code === 200) {
          const result = JSON.parse(data)
          this.optionsList = result.Result.Data || []
        }
      })
    },
    // 点击关闭
    handleClose() {
      this.publicClose()
    },
    // 公共关闭逻辑
    publicClose() {
      this.$refs.formRef.resetFields()
      this.formColumns[1].show = true
      this.formData.userList = []
      this.$emit('update:addVis', false)
      // 手动清空表单里面的表格数据
      this.formData.source = 0
      this.isShowTable = true
      this.formColumns[1].show = false
      this.formColumns[3].show = true
    },
    // 点击确认
    async handleConfirm() {
      await this.$refs.formRef.validate()
      if (this.formData.source === 0) {
        this.formData.userList.forEach(item => {
          item.username = item.mobile
        })
        this.formData.orgName = this.formData.sponsorName
      } else if (this.formData.source === 1) {
        this.formData.userIds = [this.formData.user]
      }
      this.formData.roleIds = [this.formData.roleId]
      this.$emit('createUserData', this.formData)
    },
    // 表格新增一条
    addNewOneTable() {
      const index = this.formData.userList.length
      const lastItem = this.formData.userList[index - 1]
      let flag = true
      for (const k in lastItem) {
        if (lastItem[k] === '') {
          flag = false
        }
      }
      if (flag) {
        // 区分新增和编辑状态的新增表格数据
        this.formData.userList.push({
          email: '',
          nickname: '',
          mobile: '',
          password: 'aidiyan@123456',
          id: index + '',
        })
      } else {
        this.$message.warning('请填写完上一条之后，再新增！')
      }
    },
    // 表单的表格的自定义校验
    validatorTable(rule, userList, callback) {
      // 简单检验是否为空
      if (!userList.length) {
        callback(new Error('请输入'))
      } else {
        const isEveryValueNotEmpty = userList.every(obj =>
          Object.values(obj).every(value => typeof value === 'string' && value.trim() !== '')
        )
        // 校验邮箱格式是否正确
        const emailRule =
          /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
        const flag = userList.every(item => item.email.match(emailRule))
        if (isEveryValueNotEmpty) {
          if (flag) {
            callback()
          } else {
            callback(new Error('邮箱格式不正确！'))
          }
        } else {
          callback(new Error('请输入'))
        }
      }
    },
    // 校验单位
    validatorSponsorName(rule, userList, callback) {
      if (this.optionsList.length === 0) {
        callback(new Error('请正确选择单位！'))
      } else {
        if (!this.optionsList.find(item => item.Name === this.formData.sponsorName)) {
          callback(new Error('请正确选择单位！'))
        } else {
          callback()
        }
      }
    },
    // 表单按钮切换控制角色选择显示隐藏
    handleradioGroupChange(val) {
      this.formData.userList = []
      if (val === 0) {
        this.isShowTable = true
        this.formColumns[1].show = false
        this.formColumns[3].show = true
      } else if (val === 1) {
        this.isShowTable = false
        this.formColumns[1].show = true
        this.formColumns[3].show = false
      }
    },
    // 点击删除
    handleDelete(row) {
      this.formData.userList = this.formData.userList.filter(item => {
        return item.id !== row.id
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.users_add_dia_main {
  ::v-deep .el-form {
    > .el-form-item {
      .el-form-item__content {
        margin-right: 24px !important;
        margin-left: 24px !important;
      }
    }
  }
}
</style>
